package com.example.dynamicschedule.utils;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Component
public class FileDownloadUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileDownloadUtil.class);
    //地址
    @Value("${endpoint}")
    public String endpoint /*="http://oss-cn-tianjin-tjyn-d01-a.ops.ypt.bankoftianjin.com"*/;
    @Value("${accessKeyId}")
    public String accessKeyId/*="G7rR7LpblClpXa3X"*/;
    @Value("${accessKeySecret}")
    public String accessKeySecret/*="EgOrr6IkHNr7zpXk6HwlHtTqVzeaCv"*/;
    //库名
    @Value("${bucketName}")
    public String bucketName/*="intelligentoutacall001"*/;


   /* public static void main(String[] args) throws IOException {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(date);
        String uploadJsonName = new StringBuilder("overdue/" + "tjcssys@upload@").append(format).append(".ok").toString();
       // File file = new File("M:\\test\\20200819 -(1) .json");
        //uploadOSSA(uploadJsonName, file);
         String downloadJsonName = new StringBuilder("tjcssys@download@").append("20200818").append(".json").toString();
         System.out.println(downloadJsonName);
         downLoad("overdue/"+downloadJsonName,"M:\\"+downloadJsonName);
    }*/


    /**
     * 下载
     *
     * @param remoteFile
     * @param localFile
     * @throws IOException
     */
    public void downLoad(String remoteFile, String localFile) throws IOException {

        ClientConfiguration conf = new ClientConfiguration();
        conf.setSupportCname(false);

        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
        try {
            client.getObject(new GetObjectRequest(bucketName, remoteFile), new File(localFile));
        } catch (OSSException oe) {
            logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message: " + oe.getErrorCode());
            logger.info("Error Code:       " + oe.getErrorCode());
            logger.info("Request ID:      " + oe.getRequestId());
            logger.info("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            logger.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            logger.info("Error Message: " + ce.getMessage());
        } finally {
            client.shutdown();
        }
    }

    /**
     * 下载
     *
     * @param remoteFile
     * @param localFile
     * @throws IOException
     */
    public void downLoadLocal(String remoteFile, String localFile, String fileName) throws IOException {
        File file = new File(localFile);
        if (!file.exists()) {
            file.mkdirs();
        }
        ClientConfiguration conf = new ClientConfiguration();
        conf.setSupportCname(false);

        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
        try {
            client.getObject(new GetObjectRequest(bucketName, remoteFile), new File(localFile + fileName));
        } catch (OSSException oe) {
            logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message: " + oe.getErrorCode());
            logger.info("Error Code:       " + oe.getErrorCode());
            logger.info("Request ID:      " + oe.getRequestId());
            logger.info("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            logger.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            logger.info("Error Message: " + ce.getMessage());
        } finally {
            client.shutdown();
        }
    }

    /**
     * 上传
     *
     * @param key
     * @param file
     */
    public void uploadOSS(String key, File file) {
        ClientConfiguration conf = new ClientConfiguration();
        conf.setSupportCname(false);
        // System.out.println("---------"+endpoint+"----------"+accessKeyId+"------"+accessKeySecret);
        OSSClient ossclient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
        try {
            System.out.println("Uploading a new object to OSS from a file\n");
            ossclient.putObject(new PutObjectRequest(bucketName, key, file));
        } catch (OSSException oe) {
            logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message: " + oe.getErrorMessage());
            logger.info("Error Code:       " + oe.getErrorCode());
            logger.info("Request ID:      " + oe.getRequestId());
            logger.info("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            logger.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            logger.info("Error Message: " + ce.getMessage());
        } catch (Throwable e) {
            logger.error("上传异常"+e.getMessage());
        } finally {
            ossclient.shutdown();
        }
    }

  /*  public void uploade() throws IOException {

        ClientConfiguration conf = new ClientConfiguration();
        conf.setSupportCname(false);
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
        try {
            File file = new File("/app/aigateway/overdue/activation_report_20190710.txt");
            client.putObject(new PutObjectRequest(bucketName, "myfile.txt", file));
        } catch (OSSException oe) {
            logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message: " + oe.getErrorCode());
            logger.info("Error Code:       " + oe.getErrorCode());
            logger.info("Request ID:      " + oe.getRequestId());
            logger.info("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            logger.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            logger.info("Error Message: " + ce.getMessage());
        } finally {
            client.shutdown();
        }
    }

    public URL getUrl(String key) {
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);// 生成URL
        ClientConfiguration conf = new ClientConfiguration();
        conf.setSupportCname(false);
        OSSClient ossclient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
        URL url = ossclient.generatePresignedUrl(bucketName, key, expiration);
        System.out.println(url.getPath());
        ossclient.shutdown();
        return url;
    }


    private void displayTextInputStream(InputStream input) throws IOException {
        Scanner scanner = new Scanner(input);
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        while (true) {
            String line = reader.readLine();
            if (line == null) break;
            logger.info("\t" + line);
        }
        reader.close();
    }
*/

    /**
     * wenlong  新建上传方法
     */


    public Map<String, Object> uploadOSSA(String key, File file) {
        Map<String, Object> map = new HashMap<>();
        ClientConfiguration conf = new ClientConfiguration();
        conf.setSupportCname(false);
        // System.out.println("---------"+endpoint+"----------"+accessKeyId+"------"+accessKeySecret);
        OSSClient ossclient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
        try {
            System.out.println("Uploading a new object to OSS from a file\n");
            ossclient.putObject(new PutObjectRequest(bucketName, key, file));
            map.put("result", "success");
        } catch (OSSException oe) {
            logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message: " + oe.getErrorMessage());
            logger.info("Error Code:       " + oe.getErrorCode());
            logger.info("Request ID:      " + oe.getRequestId());
            logger.info("Host ID:           " + oe.getHostId());
            map.put("result", "fail:" + oe.getErrorMessage());
        } catch (ClientException ce) {
            logger.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            logger.info("Error Message: " + ce.getMessage());
            map.put("result", "fail:" + ce.getMessage());
        } catch (Throwable e) {
            logger.error("上传异常"+e.getMessage());

            map.put("result", "fail");
        } finally {
            ossclient.shutdown();
        }
        return map;
    }

    public static String readESBJsonFile(String filePath) {
        FileReader fileReader = null;
        Reader inputStreamReader = null;
        FileInputStream fileInputStream = null;
        String intelligenceJsonStr = null;
        try {
            File file = new File(filePath);
            fileReader = new FileReader(file);
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = inputStreamReader.read()) != -1) {
                sb.append((char) ch);
            }
            intelligenceJsonStr = sb.toString();
        } catch (IOException e) {
            logger.error("上传异常"+e.getMessage());
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (Exception e) {
                logger.error("上传ESBJSON文件异常",e.getMessage());
            }
        }
        return intelligenceJsonStr;
    }

    public String readJSONFile(String filePath) {
        FileReader fileReader = null;
        Reader inputStreamReader = null;
        FileInputStream fileInputStream = null;
        String intelligenceJsonStr = null;
        try {
            File file = new File(filePath);
            fileReader = new FileReader(file);
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = inputStreamReader.read()) != -1) {
                sb.append((char) ch);
            }
            intelligenceJsonStr = sb.toString();

        } catch (IOException e) {
            logger.error("readJSONFile异常"+e.getMessage());
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                logger.error("readJSONFile异常"+e.getMessage());
            }
        }
        return intelligenceJsonStr;
    }

    public void saveFilePic(String filepath,String serverPath, String fileName) {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {

            byte[] bs = new byte[1024];
            int len;
            File tempFile = new File(serverPath);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            inputStream=new FileInputStream(filepath);
            outputStream = new FileOutputStream(tempFile + File.separator + fileName);
            while ((len = inputStream.read(bs)) != -1) {
                outputStream.write(bs, 0, len);
            }
        } catch (IOException e) {
            logger.error("saveFilePic异常"+e.getMessage());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                logger.error("saveFilePic异常"+e.getMessage());
            }
        }
    }
}
